/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package l2s.gameserver.scripting;

import com.google.common.base.Objects;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;

import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class L2ScriptLoader
{
	private static final Logger _log = LoggerFactory.getLogger(L2ScriptLoader.class.getName());
	
	private static Class<? extends ScriptFile> currentLoadingScript;
	
	private final static Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("l2s.gameserver.scripts")).filterInputsBy(new FilterBuilder().exclude("l2s.gameserver.handler")).setScanners(new SubTypesScanner(false)).useParallelExecutor());
	private final static Set<Class<? extends ScriptFile>> classes = reflections.getSubTypesOf(ScriptFile.class);
	
	public static void init()
	{
		//@formatter:off
		for (final Class<? extends ScriptFile> scriptClass : classes)
		{
			try
			{
				currentLoadingScript = scriptClass;
				
				final Method onLoadMethod = scriptClass.getMethod("onLoad");
				
				if (Objects.equal(onLoadMethod.getDeclaringClass(), scriptClass))
				{
					onLoadMethod.invoke(scriptClass);
				}
			}
			catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e)
			{
				_log.warn("Script {} can't be initialized: {}", scriptClass.getSimpleName(), e.getLocalizedMessage());
			}
		}
		//@formatter:on
	}
	
	public Class<? extends ScriptFile> getCurrentLoadingScript()
	{
		return currentLoadingScript;
	}
}